import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/entity/promotion_entity.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/set/ArticleDetail.dart';
import 'package:panda/set/JinShen.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/BaseDialog.dart';
import 'package:panda/util/SignUtil.dart';

import '../base/Constant.dart';

class MyJinShenShenHePage extends StatefulWidget {
  int type = 0;
  MyJinShenShenHePage({Key key, this.type}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return MyJinShenShenHeView();
  }
}

class MyJinShenShenHeView extends State<MyJinShenShenHePage>
    with AutomaticKeepAliveClientMixin {
  List<PromotionEntityDataData> dataList = new List();
  String group_id = "";
  int page = 1;
  String token = "", one = "", two = "", three = "";
  EasyRefreshController _controller = EasyRefreshController();
  bool isEnable = true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
      print(token);
      loadList();
      getNext();
    });
  }

  getNext() async {
    Map map = new Map();
    map['token'] = token;
    map['sign_type'] = SignType.GET_NEXT_GROUP;
    Response<String> response =
        await HttpUtil().post(Api.GET_NEXT_GROUP, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    if (code == 1 && mounted) {
      setState(() {
        isEnable = false;
      });
    } else {
      // Fluttertoast.showToast(msg: msg);

      setState(() {});
    }
  }

  loadList() async {
    Map map = new Map();
    map['token'] = token;
    map['p'] = page.toString();
    map['per'] = "10";
    map['type'] = widget.type;
    map['sign_type'] = SignType.GETPROMOTIONLIST;
    Response<String> response = await HttpUtil().post(
        widget.type == 1
            ? Api.BaseUrl + "/index.php/wap/UserUpgradeApply/user"
            : widget.type == 2 ? Api.GETPROMOTIONLIST : Api.GETPROMOTIONLIST2,
        data: getSign(map));
    Map userMap = json.decode(response.data);
    if (mounted) if (page == 1) {
      _controller.finishRefresh();
    } else {
      _controller.finishLoad();
    }
    if (userMap['code'] != 1) {
      Fluttertoast.showToast(msg: userMap['msg']);
      return;
    }
    PromotionEntityEntity homeListEntity =
        new PromotionEntityEntity.fromJson(userMap);
    if (mounted)
      setState(() {
        if (page == 1) {
          dataList.clear();
          dataList.addAll(homeListEntity.data.datas);
        } else {
          dataList.addAll(homeListEntity.data.datas);
        }
      });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

    return new Scaffold(
      body: new Container(
          color: divideColor,
          child: Column(
            children: <Widget>[
              Expanded(
                child: new EasyRefresh(
                  enableControlFinishRefresh: true,
                  enableControlFinishLoad: true,
                  header: MaterialHeader(),
                  footer: MaterialFooter(),
                  controller: _controller,
                  child: ListView.separated(
                      itemBuilder: _renderRow,
                      separatorBuilder: (BuildContext context, int index) {
                        return Container(
                          color: divideColor,
                          height: 1,
                        );
                      },
                      itemCount: dataList.length),
                  onRefresh: () async {
                    page = 1;
                    loadList();
                  },
                  onLoad: () async {
                    page++;
                    loadList();
                  },
                ),
              ),
              Offstage(
                offstage: isEnable,
                child: new Container(
                  width: double.infinity,
                  height: ScreenUtil.getInstance().setHeight(70),
                  margin: EdgeInsets.fromLTRB(60, 20, 60, 50),
                  decoration: new BoxDecoration(
                      color: mainColor,
                      borderRadius: BorderRadius.circular(
                          ScreenUtil.getInstance().setHeight(DP_10))),
                  padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
                  child: new FlatButton(
                    child: new Padding(
                      padding: EdgeInsets.all(0.0),
                      child: new Text(
                        "我要升级",
                        style: new TextStyle(color: Colors.white, fontSize: 16),
                      ),
                    ),
                    onPressed: () {
                      showMyDialog();
                      // Navigator.of(context).push<String>(
                      //     new MaterialPageRoute(builder: (context) {
                      //   return new JinShenPage();
                      // })).then((value) {
                      //   if (value != null) {
                      //     page = 1;
                      //     loadList();
                      //   }
                      // });
                    },
                  ),
                ),
              )
            ],
          )),
    );
  }

  var myState;
  void showMyDialog() {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return StatefulBuilder(builder: (context, state) {
            myState = state;
            return BaseDialog(
                Column(
                  children: <Widget>[
                    Container(
                      margin: EdgeInsets.only(top: 20),
                      alignment: Alignment.center,
                      child: Text(
                        "选择晋升等级",
                        style: TextStyle(
                            fontSize: 18, letterSpacing: 2, color: mainColor),
                      ),
                    ),
                    Expanded(
                      child: Container(
                        padding: EdgeInsets.all(10),
                        child: Column(
                          children: <Widget>[
                            Row(
                              children: <Widget>[
                                Expanded(
                                    child: Text('晋升经理',
                                        style: TextStyle(
                                            fontSize: 14, color: black))),
                                Checkbox(
                                    value: group_id == "3",
                                    activeColor: mainColor,
                                    checkColor: white,
                                    materialTapTargetSize:
                                        MaterialTapTargetSize.padded,
                                    onChanged: (bool x) {
                                      if (x) {
                                        group_id = "3";
                                      }
                                      myState(() {});
                                    }),
                              ],
                            ),
                            Divider(
                              height: 1,
                            ),
                            Row(
                              children: <Widget>[
                                Expanded(
                                    child: Text('晋升总监',
                                        style: TextStyle(
                                            fontSize: 14, color: black))),
                                Checkbox(
                                    value: group_id == "4",
                                    activeColor: mainColor,
                                    checkColor: white,
                                    materialTapTargetSize:
                                        MaterialTapTargetSize.padded,
                                    onChanged: (bool x) {
                                      if (x) {
                                        group_id = "4";
                                      }
                                      myState(() {});
                                    }),
                              ],
                            ),
                            Divider(
                              height: 1,
                            ),
                            Container(height:20),
                            GestureDetector(
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  Text(
                                    '申请则视为同意',
                                    style: TextStyle(
                                        color: black,
                                        fontSize:
                                            ScreenUtil.getInstance().setSp(25)),
                                  ),
                                  Text(
                                    '《熊猫新零售晋升制度》',
                                    style: TextStyle(
                                        color: mainColor,
                                        fontSize:
                                            ScreenUtil.getInstance().setSp(28)),
                                  ),
                                ],
                              ),
                              onTap: () {
                                Navigator.of(context)
                                    .push(MaterialPageRoute(builder: (context) {
                                  return new ArticleDetailPage(
                                    article_id: "52",
                                  );
                                }));
                              },
                            ),
                          ],
                        ),
                      ),
                    ),
                    Container(
                      height: 50,
                      width: double.infinity,
                      margin: EdgeInsets.only(top: 10),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          InkWell(
                              onTap: () {
                                up1();
                              },
                              child: Container(
                                margin: EdgeInsets.only(bottom: 20),
                                alignment: Alignment.center,
                                width: 100,
                                height: 30,
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(15),
                                    color: mainColor),
                                child: Text(
                                  "确定提交",
                                  style: TextStyle(
                                      letterSpacing: 3, color: Colors.white),
                                ),
                              ))
                        ],
                      ),
                    )
                  ],
                ),
                MediaQuery.of(context).size.width*.7,
                MediaQuery.of(context).size.width * .8);
          });
        });
  }

  up1() async {
    Map map = new Map();
    map['token'] = token;
    map['group_id'] = group_id;
    Response<String> response = await HttpUtil().post(
        Api.BaseUrl + "/index.php/wap/UserUpgradeApply/apply",
        data: getSign(map));
    Map userMap = json.decode(response.data);
    Navigator.of(context).pop(1);
    Fluttertoast.showToast(msg: userMap['msg']);
    if (userMap['code'] == 1 && mounted) {
      // Navigator.of(context).pop("1");
      // APPLIC.userInfoMap=userMap['data'];
      // APPLIC.eventBus.fire(UserInfoEvent(APPLIC.userInfoMap));
    }
  }

  Widget _renderRow(BuildContext context, int index) {
    return new GestureDetector(
      child: new Container(
        color: Colors.white,
        padding: EdgeInsets.all(15.0),
        margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Offstage(
              child: Row(children: <Widget>[
                Expanded(
                  child: Center(),
                ),
                Text(
                  dataList[index].status_zh,
                  style: TextStyle(color: mainColor, fontSize: 14),
                ),
              ]),
              offstage: false,
            ),
            Row(children: <Widget>[
              Container(
                width: 80,
                child: Text(
                  '申请人',
                  style: TextStyle(color: black, fontSize: 14),
                ),
              ),
              Container(
                width: 15,
              ),
              Expanded(
                child: Text(
                  dataList[index].username == null
                      ? ""
                      : dataList[index].username,
                  style: TextStyle(color: Colors.black54, fontSize: 14),
                ),
              ),
            ]),
            Container(
              height: 5,
            ),
            Row(children: <Widget>[
              Container(
                width: 80,
                child: Text(
                  '申请时间',
                  style: TextStyle(color: black, fontSize: 14),
                ),
              ),
              Container(
                width: 15,
              ),
              Expanded(
                child: Text(
                  dataList[index].create_time,
                  style: TextStyle(color: Colors.black54, fontSize: 14),
                ),
              ),
            ]),
            Container(
              height: 5,
            ),
            Row(children: <Widget>[
              Container(
                width: 80,
                child: Text(
                  '申请级别',
                  style: TextStyle(color: black, fontSize: 14),
                ),
              ),
              Container(
                width: 15,
              ),
              Expanded(
                child: Text(
                  dataList[index].group_name,
                  style: TextStyle(color: Colors.black54, fontSize: 14),
                ),
              ),
            ]),
            Container(
              height: 5,
            ),
            Offstage(
              offstage: dataList[index].status != "1",
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    GestureDetector(
                        child: Container(
                          width: DP_60,
                          padding: EdgeInsets.all(6),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            color: Colors.grey,
                            borderRadius: BorderRadius.circular(3.0),
                          ),
                          child: Text('拒绝',
                              style: TextStyle(color: black_99, fontSize: 16)),
                        ),
                        onTap: () {
                          showDialog(
                            context: context,
                            builder: (context) => new AlertDialog(
                              title: new Text('提示'),
                              content: new Text('审核结果提交后，不可撤回,请谨慎操作'),
                              actions: <Widget>[
                                new FlatButton(
                                  onPressed: () {
                                    Navigator.of(context).pop(false);
                                  },
                                  child: new Text(
                                    '取消',
                                    style: TextStyle(color: Colors.grey),
                                  ),
                                ),
                                new FlatButton(
                                  onPressed: () {
                                    Navigator.of(context).pop(false);
                                    del(index, "N");
                                  },
                                  child: new Text('确定',
                                      style: TextStyle(color: mainColor)),
                                ),
                              ],
                            ),
                          );
                        }),
                    GestureDetector(
                        child: Container(
                          width: DP_60,
                          padding: EdgeInsets.all(6),
                          alignment: Alignment.center,
                          margin: EdgeInsets.only(left: 10),
                          decoration: BoxDecoration(
                            color: mainColor,
                            borderRadius: BorderRadius.circular(3.0),
                          ),
                          child: Text('通过',
                              style: TextStyle(color: white, fontSize: 16)),
                        ),
                        onTap: () {
                          showDialog(
                            context: context,
                            builder: (context) => new AlertDialog(
                              title: new Text('提示'),
                              content: new Text('审核结果提交后，不可撤回,请谨慎操作'),
                              actions: <Widget>[
                                new FlatButton(
                                  onPressed: () {
                                    Navigator.of(context).pop(false);
                                  },
                                  child: new Text(
                                    '取消',
                                    style: TextStyle(color: Colors.grey),
                                  ),
                                ),
                                new FlatButton(
                                  onPressed: () {
                                    Navigator.of(context).pop(false);
                                    del(index, "Y");
                                  },
                                  child: new Text('确定',
                                      style: TextStyle(color: mainColor)),
                                ),
                              ],
                            ),
                          );
                        })
                  ]),
            )
          ],
        ),
      ),
      onTap: () {
        if (widget.type == 1) {
          // Navigator.of(context).pop(dataList[index]);
        }
      },
    );
  }

  del(int index, String result) async {
    submit(index, result);
  }

  submit(int index, String result) async {
    Map map = new Map();
    map['token'] = token;
    map['id'] = dataList[index].id;
    map['check'] = result;
    map['sign_type'] = SignType.CHECKPROMOTION;
    print(map);
    Response<String> response = await HttpUtil().post(
        Api.BaseUrl + "/index.php/wap/UserUpgradeApply/examine",
        data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Fluttertoast.showToast(msg: msg);
    if (code == 1 && mounted) {
      page = 1;
      loadList();
    }
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
